package com.baiye.template.config;

import com.google.gson.Gson;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author GUOZHIPENG
 * @version 1.0
 * @date 2021/10/27 19:03
 * 匿名用户访问无权限资源时的异常
 */

@Component
public class CustomizeAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e){
        httpServletResponse.setContentType("text/json;charset=utf-8");
        try {
            httpServletResponse.getWriter().write(new Gson().toJson("未登录或权限不足"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

